package cn.edu.sjtu.se.dslab.component.aadl;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.sjtu.se.dslab.component.data.AvionicsEquipment;
import cn.edu.sjtu.se.dslab.rhapsody.entity.Agent;
import cn.edu.sjtu.se.dslab.rhapsody.entity.BusAgent;
import cn.edu.sjtu.se.dslab.rhapsody.entity.ControlAgent;
import cn.edu.sjtu.se.dslab.rhapsody.entity.DisplayAgent;
import cn.edu.sjtu.se.dslab.service.IAvionicsEquipmentService;
import cn.edu.sjtu.se.dslab.util.Const;

import com.sun.tools.javac.util.PropagatedException;

/**
 * aadl解析类service
 * 
 * @author sunke
 * 
 */
@Service("aadlParser")
@Transactional
public class AADLParser {
	
	private static final Logger LOG = Logger.getLogger(AADLParser.class);

	private final static String CONTENT = "content";
	private final static String NODE = "node";
	private final static String NODE_ID = "id";
	private final static String NODE_TYPE = "type";
	private final static String NODE_SUBTYPE = "subtype";
	private final static String NODE_ISMAIN = "isMain";
	private final static String NODE_NAME = "name";
	private final static String NODE_DBID = "dbid";
	private final static String NODE_PARENTID = "parentid";
	private final static String NODE_HASCHILD = "haschild";
	private final static String NODE_X = "x";
	private final static String NODE_Y = "y";
	private final static String NODE_WIDTH = "width";
	private final static String NODE_HEIGHT = "height";
	
	private final static String PAPER_WIDTH = "width";
	private final static String PAPER_HEIGHT = "height";

	private final static String NODE_FEATURES = "features";
	private final static String NODE_FEATURE_PROT = "port";
	private final static String NODE_FEATURE_NAME = "name";
	private final static String NODE_FEATURE_TYPE = "type";

	private final static String NODE_PROPERTIES = "properties";
	private final static String NODE_PROPERTIES_PROPERTY = "property";
	private final static String NODE_PROPERTIES_NAME = "name";
	private final static String NODE_PROPERTIES_VALUE = "value";

	private final static String LINK = "link";
	private final static String LINK_SOURCEID = "sourceid";
	private final static String LINK_SOURCEPORT = "sourceport";
	private final static String LINK_TAEGETID = "targetid";
	private final static String LINK_TARGETPORT = "targetport";
	private final static String LINK_TYPE = "type";

	@Resource(name = "avionicsEquipmentService")
	IAvionicsEquipmentService avionicsEquipmentService;

	private final static String SYSTEM_COMPLETE = "complete";

	public List<AADLNode> parseAADLToNode(Document document) {
		try {
			Element rootElm = document.getRootElement();
			if (rootElm.getName().equals(CONTENT)) {
				// 解析所有的node
				List<Element> nodes = rootElm.elements(NODE);
				List<AADLNode> nodeList = new ArrayList<AADLNode>();
				for (Iterator<Element> it = nodes.iterator(); it.hasNext();) {
					Element element = (Element) it.next();
					AADLNode node = new AADLNode();
					// node的属性
					List<Element> items = element.elements();
					for (int i = 0; i < items.size(); i++) {
						Element item = items.get(i);
						if (item.getName().equals(NODE_ID)) {
							node.setId(item.getTextTrim());
						} else if (item.getName().equals(NODE_TYPE)) {
							node.setType(item.getTextTrim());
						} else if (item.getName().equals(NODE_SUBTYPE)) {
							node.setSubtype(item.getTextTrim());
						} else if (item.getName().equals(NODE_ISMAIN)) {
							node.setIsMain(item.getTextTrim());
						} else if (item.getName().equals(NODE_NAME)) {
							node.setName(item.getTextTrim());
						} else if (item.getName().equals(NODE_DBID)) {
							String temp = item.getTextTrim();
							if (temp != null && !temp.equals("")) {
								node.setDb_id(Long.parseLong(temp));
							}
						} else if (item.getName().equals(NODE_PARENTID)) {
							node.setParent_id(item.getTextTrim());
						} else if (item.getName().equals(NODE_HASCHILD)) {
							String temp = item.getTextTrim();
							if (temp != null && !temp.equals("")) {
								node.setHasChild(Boolean.parseBoolean(temp));
							}
						} else if (item.getName().equals(NODE_X)) {
							String temp = item.getTextTrim();
							if (temp != null && !temp.equals("")) {
								node.setX(Integer.parseInt(temp));
							}
						} else if (item.getName().equals(NODE_Y)) {
							String temp = item.getTextTrim();
							if (temp != null && !temp.equals("")) {
								node.setY(Integer.parseInt(temp));
							}
						} else if (item.getName().equals(NODE_WIDTH)) {
							String temp = item.getTextTrim();
							if (temp != null && !temp.equals("")) {
								node.setWidth(Integer.parseInt(temp));
							}
						} else if (item.getName().equals(NODE_HEIGHT)) {
							String temp = item.getTextTrim();
							if (temp != null && !temp.equals("")) {
								node.setHeight(Integer.parseInt(temp));
							}
						}// node的feature属性
						else if (item.getName().equals(NODE_FEATURES)) {
							List<Element> links = item
									.elements(NODE_FEATURE_PROT);
							List<AADLFeature> featureList = new ArrayList<AADLFeature>();
							// node的feature单项属性
							for (Iterator<Element> itLink = links.iterator(); itLink
									.hasNext();) {
								Element elementLink = (Element) itLink.next();
								AADLFeature feature = new AADLFeature();
								List<Element> properties = elementLink
										.elements();
								for (int j = 0; j < properties.size(); j++) {
									Element linkProperty = properties.get(j);
									if (linkProperty.getName().equals(
											NODE_FEATURE_NAME)) {
										feature.setName(linkProperty
												.getTextTrim());
									} else if (linkProperty.getName().equals(
											NODE_FEATURE_TYPE)) {
										feature.setType(parseFeatureType(linkProperty
												.getTextTrim()));
									}
								}// end port
								featureList.add(feature);
							}// end feature
							node.setFeatures(featureList);
						}// end else if-->features
							// node的properties属性
						else if (item.getName().equals(NODE_PROPERTIES)) {
							List<Element> pros = item
									.elements(NODE_PROPERTIES_PROPERTY);
							List<AADLProperty> propertyList = new ArrayList<AADLProperty>();
							// node的property单项属性
							for (Iterator<Element> itLink = pros.iterator(); itLink
									.hasNext();) {
								Element elementLink = (Element) itLink.next();
								List<Element> properties = elementLink
										.elements();
								String name = "";
								String value = "";
								for (int j = 0; j < properties.size(); j++) {
									Element linkProperty = properties.get(j);
									if (linkProperty.getName().equals(
											NODE_PROPERTIES_NAME)) {
										name = linkProperty.getTextTrim();
									} else if (linkProperty.getName().equals(
											NODE_PROPERTIES_VALUE)) {
										value = linkProperty.getTextTrim();
									}
								}// end property
								propertyList.add(new AADLProperty(name, value));
							}// end property
							node.setProperties(propertyList);
						}// end else if-->properties
					}// end所有的属性
					nodeList.add(node);
				}
				return nodeList;
			} else {
				return null;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		return null;
	}

	private String parseFeatureType(String imgType) {
		if (imgType.equals("In Data Port")) {
			return "in data port";
		} else if (imgType.equals("Out Data Port")) {
			return "out data port";
		} else if (imgType.equals("InOut Data Port")) {
			return "in out data port";
		} else if (imgType.equals("In Event Port")) {
			return "in event port";
		} else if (imgType.equals("Out Event Port")) {
			return "out event port";
		} else if (imgType.equals("InOut Event Port")) {
			return "in out event port";
		} else if (imgType.equals("In DataEvent Port")) {
			return "in event data port";
		} else if (imgType.equals("Out DataEvent Port")) {
			return "out event data port";
		} else if (imgType.equals("InOut DataEvent Port")) {
			return "in out event data port";
		} else if (imgType.equals("Requires Data Access")) {
			return "requires data access";
		} else if (imgType.equals("Provides Data Access")) {
			return "provides data access";
		} else if (imgType.equals("Requires Bus Access")) {
			return "requires bus access";
		} else if (imgType.equals("Provides Bus Access")) {
			return "provides bus access";
		}
		return "";
	}

	public List<AADLNode> parseAADLToNode(String xml) {
		try {
			Document document = DocumentHelper.parseText(xml);
			return parseAADLToNode(document);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}

	public List<AADLNode> parseAADLToNode(File inputXml) {
		try {
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(inputXml);
			return parseAADLToNode(document);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}
	
	public int parseAADLToHeight(File inputXml) {
		try {
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(inputXml);
			Element rootElm = document.getRootElement();
			if (rootElm.getName().equals(CONTENT)) {
				Attribute attribute = rootElm.attribute(PAPER_HEIGHT);
				if ( attribute != null) {
					String result = attribute.getStringValue();
					return Integer.parseInt(result);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return 800;
	}
	
	public int parseAADLToWidth(File inputXml) {
		try {
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(inputXml);
			Element rootElm = document.getRootElement();
			if (rootElm.getName().equals(CONTENT)) {
				Attribute attribute = rootElm.attribute(PAPER_WIDTH);
				if ( attribute != null) {
					String result = attribute.getStringValue();
					return Integer.parseInt(result);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return 1200;
	}

	public List<AADLLink> parseAADLToLink(String xml) {
		try {
			Document document = DocumentHelper.parseText(xml);
			return parseAADLToLink(document);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}

	public List<AADLLink> parseAADLToLink(File inputXml) {
		try {
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(inputXml);
			return parseAADLToLink(document);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}

	// 根据xml文件路径，解析获取设备list
	public List<AvionicsEquipment> parseAADLToEquipmentList(File inputXml) {
		try {
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(inputXml);
			List<AADLNode> nodeList = parseAADLToNode(document);
			List<AvionicsEquipment> equipmentList = new ArrayList<AvionicsEquipment>();
			for (int i = 0; i < nodeList.size(); i++) {
				AADLNode node = nodeList.get(i);
				if (node.getDb_id() != 0) {
					AvionicsEquipment equipment = avionicsEquipmentService
							.getAvionicsEquipmentById(node.getDb_id());
					if (equipment != null) {
						equipmentList.add(equipment);
					}
				}
			}
			return equipmentList;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 根据xml文件路径，解析获取sysml对应的actor列表
	 * @param inputXml
	 * @return
	 */
	public List<AvionicsEquipment> parseAADLToSysmlActor(File inputXml) {
		try {
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(inputXml);
			List<AADLNode> nodeList = parseAADLToNode(document);
			List<AvionicsEquipment> equipmentList = new ArrayList<AvionicsEquipment>();
			for (int i = 0; i < nodeList.size(); i++) {				
				AADLNode node = nodeList.get(i);
				/*System.out.println(""+node.getName());
				System.out.println(""+node.getType());*/
				if ((node.getDb_id() != 0) && node.getType().equals(Const.AADL_DIAGRAM_TYPE_DEVICE)&& node.getSubtype().equals(Const.AADL_DIAGRAM_TYPE_OUTTER_DEVICE)) {
					AvionicsEquipment equipment = avionicsEquipmentService
							.getAvionicsEquipmentById(node.getDb_id());
					if (equipment != null && equipment.getEquiptype().equals(AvionicsEquipment.EQUIPMENT_TYPE_OUTTER_DEVICE)) {
						equipmentList.add(equipment);
					}
				}
			}
			return equipmentList;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}
	
	private final static String TYPE_SUBPROGRAM = "subprogram";
	
	/**
	 * 根据xml文件路径，解析获取对应的agent数组list，一个map元素的value是一个数组，该数组中的agent属于一个thread（map元素的key）
	 * @param inputXml
	 * @return
	 */
	public Map<String, Set<Agent>> parseAADLToAgentArrayList(File inputXml) {
		try {
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(inputXml);
			List<AADLNode> nodeList = parseAADLToNode(document);
			Map<String, AADLNode> searchMap = new HashMap<String, AADLNode>();
			if (nodeList != null) {
				for (AADLNode aadlNode : nodeList) {
					searchMap.put(aadlNode.getId(), aadlNode);
				}
			}
			//AADLNode-->thread set-->对应的agent
			Map<String, Set<Agent>> map = new HashMap<String, Set<Agent>>();
			
			for (int i = 0; i < nodeList.size(); i++) {				
				AADLNode node = nodeList.get(i);
				/*System.out.println(""+node.getName());
				System.out.println(""+node.getType());*/
				if (node.getType().equals(TYPE_SUBPROGRAM)) {
					String parentId = node.getParent_id();
					AADLNode parentNode = searchMap.get(parentId);
					if (parentNode != null) {
						String parentName = parentNode.getName();
						Agent agent = null;
						if (map.get(parentName) == null) {
							Set<Agent> set = new HashSet<Agent>();
							map.put(parentName, set);
						}
						List<AADLProperty> properties =  node.getProperties();
						if (properties != null) {
							for (AADLProperty aadlProperty : properties) {
								if(aadlProperty.getName().equals("subprogram_type")){
									String value = aadlProperty.getValue();
									LOG.info("Property value =" + value);
									if (value.equals("bus_read") || value.equals("bus_write")||value.equals("bus")) {
										agent = new BusAgent();
										agent.setName(node.getName());
									}else if (value.equals("display")) {
										agent = new DisplayAgent();
										agent.setName(node.getName());
									}else if (value.equals("control")) {
										agent = new ControlAgent();
										agent.setName(node.getName());
									}
									break;
								}
							}
							map.get(parentName).add(agent);
						}
						
					}
				}
			}
			return map;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 * 根据xml文件路径，解析获取主系统对应的内部system  其中，内部主系统的getIsMain返回Const.AADL_DIAGRAM_TYPE_ISMAIN_SYSTEM
	 * @param inputXml
	 * @return
	 */
	public List<AADLNode> parseAADLToInnerSystem(File inputXml) {
		try {
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(inputXml);
			List<AADLNode> nodeList = parseAADLToNode(document);
			List<AADLNode> innerSystems = new ArrayList<AADLNode>();
			AADLNode mainSystem = null;
			//遍历检索主系统
			for (AADLNode aadlNode : nodeList) {
				if (aadlNode.getSubtype().equals(Const.AADL_DIAGRAM_TYPE_MAIN_SYSTEM) && aadlNode.isHasChild()) {
					mainSystem = aadlNode;
				}
			}
			//获取主系统内的内部子系统
			for (int i = 0; i < nodeList.size(); i++) {				
				AADLNode node = nodeList.get(i);
				/*System.out.println(""+node.getName());
				System.out.println(""+node.getType());*/
				if ((node.getType()== null)?false:node.getType().equals(Const.AADL_DIAGRAM_TYPE_SYSTEM)
						&& (node.getSubtype()== null)?false:node.getSubtype().equals(Const.AADL_DIAGRAM_TYPE_INNER_SYSTEM)  
						&& (node.getParent_id()== null)?false:node.getParent_id().equals(mainSystem.getId())) {
					innerSystems.add(node);
				}
			}
			return innerSystems;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}

	public List<AADLLink> parseAADLToLink(Document document) {
		try {
			Element rootElm = document.getRootElement();
			if (rootElm.getName().equals(CONTENT)) {
				// 解析所有的link
				List<Element> links = rootElm.elements(LINK);
				List<AADLLink> linkList = new ArrayList<AADLLink>();
				for (Iterator it = links.iterator(); it.hasNext();) {
					Element elm = (Element) it.next();
					List<Element> items = elm.elements();
					AADLLink aadlLink = new AADLLink();
					for (int j = 0; j < items.size(); j++) {
						Element linkProperty = items.get(j);

						if (linkProperty.getName().equals(LINK_SOURCEID)) {
							aadlLink.setSourceId(linkProperty.getTextTrim());
						} else if (linkProperty.getName().equals(
								LINK_SOURCEPORT)) {
							aadlLink.setSourcePort(linkProperty.getTextTrim());
						} else if (linkProperty.getName().equals(LINK_TAEGETID)) {
							aadlLink.setTargetId(linkProperty.getTextTrim());
						} else if (linkProperty.getName().equals(
								LINK_TARGETPORT)) {
							aadlLink.setTargetPort(linkProperty.getTextTrim());
						} else if (linkProperty.getName().equals(LINK_TYPE)) {
							aadlLink.setType(linkProperty.getTextTrim());
						}

					}
					linkList.add(aadlLink);
				}
				return linkList;
			} else {
				return null;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		return null;
	}

	public Set<AADLElement> parseAADL(String xml) {
		List<AADLNode> nodeList = parseAADLToNode(xml);
		List<AADLLink> linkList = parseAADLToLink(xml);
		Map<String, AADLNode> searchMap = new HashMap<String, AADLNode>();
		Map<String, AADLElement> nameMap = new HashMap<String, AADLElement>();
		// 系统默认添加complete system
		AADLElement complete = new AADLElement();
		// 处理名称
		complete.setName(SYSTEM_COMPLETE);
		// 处理类型
		complete.setType("system");
		nameMap.put(SYSTEM_COMPLETE, complete);
		for (int i = 0; i < nodeList.size(); i++) {
			searchMap.put(nodeList.get(i).getId(), nodeList.get(i));
			AADLElement element = new AADLElement();
			nameMap.put(nodeList.get(i).getName(), element);
		/*	// device类型，默认内嵌process
			if (nodeList.get(i).getType().trim().toLowerCase().equals("device")) {
				AADLElement process = new AADLElement();
				nameMap.put(nodeList.get(i).getName() + "_process", process);
			}*/
		}

		// Map<String, AADLElement> idMap = new HashMap<String, AADLElement>();
		// 遍历nodelist构建aadlElement
		for (int i = 0; i < nodeList.size(); i++) {
			AADLNode node = nodeList.get(i);
			if (node.isHasChild()) {
				continue;
			} else {
				AADLElement element = nameMap.get(node.getName());
				// 处理名称
				element.setName(node.getName());
				// 处理类型
				element.setType(node.getType().trim().toLowerCase());
				// 处理features
				if (node.getFeatures() != null) {
					Set<ContentPair> features = new HashSet<ContentPair>();
					for (int j = 0; j < node.getFeatures().size(); j++) {
						AADLFeature feature = node.getFeatures().get(j);
						ContentPair pair = new ContentPair(feature.getName(),
								feature.getType());
						features.add(pair);
					}
					element.setFeatures(features);
				}
				// 处理properties
				if (node.getProperties() != null) {
					Set<ContentPair> properties = new HashSet<ContentPair>();
					for (int j = 0; j < node.getProperties().size(); j++) {
						AADLProperty property = node.getProperties().get(j);
						ContentPair pair = new ContentPair(property.getName(),
								property.getValue());
						properties.add(pair);
					}
					element.setProperties(properties);
				}
				// 处理parent
				String parentId = node.getParent_id();
				AADLElement parentElement;
				if (parentId != null && !parentId.equals("")
						&& !parentId.equals("null")) {
					parentElement = nameMap.get(searchMap.get(parentId)
							.getName());
				} else {
					parentElement = nameMap.get(SYSTEM_COMPLETE);
				}
				/*if (parentElement.getType().equals("device")) {
					parentElement = nameMap.get(searchMap.get(parentId)
							.getName() + "_process");
				}*/
				ContentPair pair = new ContentPair(node.getName(), node
						.getType().trim().toLowerCase()
						+ " " + node.getName() + "_aadl." + node.getName());
				if (parentElement.getSubcomponents() == null) {
					Set<ContentPair> subcomponents = new HashSet<ContentPair>();
					parentElement.setSubcomponents(subcomponents);
				}
				parentElement.getSubcomponents().add(pair);

				/*// device类型，默认内嵌process
				if (node.getType().trim().toLowerCase().equals("device")) {
					String name = node.getName() + "_process";
					AADLElement process = nameMap.get(name);
					// 处理名称
					process.setName(name);
					// 处理类型
					process.setType("process");
					process.setFeatures(element.getFeatures());
					ContentPair tpair = new ContentPair(name, "process" + " "
							+ name + "_aadl." + name);
					if (element.getSubcomponents() == null) {
						Set<ContentPair> subcomponents = new HashSet<ContentPair>();
						element.setSubcomponents(subcomponents);
					}
					element.getSubcomponents().add(tpair);

				}*/
			}
		}
		// 遍历linkList填充aadlElement的connections
		int dataIndex = 0;
		int busAccessIndex = 0;
		int eventIndex = 0;
		int dataEventIndex = 0;
		int dataAccessIndex = 0;
		for (int i = 0; i < linkList.size(); i++) {
			AADLLink link = linkList.get(i);
			String sourceid = link.getSourceId();
			String sourcePort = link.getSourcePort();
			String targetid = link.getTargetId();
			String targetPort = link.getTargetPort();
			// 交换顺序错误的境况
			// if(sourcePort.contains("In") || sourcePort.contains("Requires")){
			// String temp = sourceid;
			// sourceid = targetid;
			// targetid = temp;
			// temp = sourcePort;
			// sourcePort = targetPort;
			// targetPort = temp;
			// }
			StringBuffer value = new StringBuffer();
			StringBuffer name = new StringBuffer();
			String devicePort = "";
			String deviceValue = "";
			String temp = sourcePort + " " + targetPort;
			if (temp.contains("In Data:") || temp.contains("Out Data:")
					|| temp.contains("InOut Data:")) {
				value.append("data port ");
				deviceValue = value.toString();
				dataIndex++;
				name.append("DataConnection" + dataIndex);
			} else if (temp.contains("Requires Bus:")
					|| temp.contains("Provides Bus:")) {
				value.append("bus access ");
				deviceValue = value.toString();
				busAccessIndex++;
				name.append("BusAccessConnection" + busAccessIndex);
			} else if (temp.contains("In Event:")
					|| temp.contains("Out Event:")
					|| temp.contains("InOut Event:")) {
				value.append("event port ");
				deviceValue = value.toString();
				eventIndex++;
				name.append("EventConnection" + eventIndex);
			} else if (temp.contains("In DataEvent:")
					|| temp.contains("Out DataEvent:")
					|| temp.contains("InOut DataEvent:")) {
				value.append("event data port ");
				deviceValue = value.toString();
				dataEventIndex++;
				name.append("EventDataConnection" + dataEventIndex);
			} else if (temp.contains("Requires Data:")
					|| temp.contains("Provides Data:")) {
				value.append("data access ");
				deviceValue = value.toString();
				dataAccessIndex++;
				name.append("DataAccessConnection" + dataAccessIndex);
			}
			String elementId = targetid;
			boolean deviceFlag = false;
			// same level
			if ((searchMap.get(sourceid).getParent_id() == null && searchMap
					.get(targetid).getParent_id() == null)
					|| searchMap.get(sourceid).getParent_id()
							.equals(searchMap.get(targetid).getParent_id())) {
				elementId = searchMap.get(sourceid).getParent_id();
				String sourceNodeName = searchMap.get(sourceid).getName();
				value.append(sourceNodeName);
				String sourcePortName = "";
				if (sourcePort.contains(":")) {
					sourcePortName = sourcePort.split(":")[1];
					value.append("." + sourcePortName + " -> ");
				} else { // 直接与结点相连
					value.append(" -> ");
				}
				String targetNodeName = searchMap.get(targetid).getName();
				value.append(targetNodeName);
				String targetPortName = "";
				if (targetPort.contains(":")) {
					targetPortName = targetPort.split(":")[1];
					value.append("." + targetPortName);
				}
			}// targetid -->parent
			else if (searchMap.get(sourceid).getParent_id().equals(targetid)) {
				String sourceNodeName = searchMap.get(sourceid).getName();
				value.append(sourceNodeName);
				String sourcePortName = "";
				if (sourcePort.contains(":")) {
					sourcePortName = sourcePort.split(":")[1];
					value.append("." + sourcePortName + " -> ");
				} else {
					value.append(" -> ");
				}
				String targetPortName = targetPort.split(":")[1];
				value.append(targetPortName);

				/*if (searchMap.get(targetid).getType().equals("device")) {
					deviceFlag = true;
					devicePort = deviceValue
							+ searchMap.get(targetid).getName() + "_process."
							+ targetPortName + " -> " + targetPortName;
				}*/
			}// sourceid -->parent
			else if (sourceid.equals(searchMap.get(targetid).getParent_id())) {
				elementId = sourceid;
				String sourcePortName = sourcePort.split(":")[1];
				value.append(sourcePortName + " -> ");
				String targetNodeName = searchMap.get(targetid).getName();
				value.append(targetNodeName);
				String targetPortName = "";
				if (targetPort.contains(":")) {
					targetPortName = targetPort.split(":")[1];
					value.append("." + targetPortName);
				}
				/*if (searchMap.get(sourceid).getType().equals("device")) {
					deviceFlag = true;
					devicePort = deviceValue + sourcePortName + " -> "
							+ searchMap.get(targetid).getName() + "_process."
							+ sourcePortName;
				}*/
			}
			AADLElement parentElement = null;
			// System.out.println("elementId:"+elementId);
			AADLNode tempNode = searchMap.get(elementId);
			if (tempNode == null) {
				parentElement = nameMap.get(SYSTEM_COMPLETE);
			} else {
				parentElement = nameMap.get(tempNode.getName());
			}
			if (parentElement != null) {
				/*if (deviceFlag) {
					ContentPair pair = new ContentPair(name.toString(),
							devicePort);
					if (parentElement.getConnections() == null) {
						Set<ContentPair> connections = new HashSet<ContentPair>();
						parentElement.setConnections(connections);
					}
					parentElement.getConnections().add(pair);
					parentElement = nameMap.get(searchMap.get(elementId)
							.getName() + "_process");
				}*/
				ContentPair pair = new ContentPair(name.toString(),
						value.toString());
				if (parentElement.getConnections() == null) {
					Set<ContentPair> connections = new HashSet<ContentPair>();
					parentElement.setConnections(connections);
				}
				parentElement.getConnections().add(pair);
			}
		}
		Set<AADLElement> result = new HashSet<AADLElement>(nameMap.values());
		return result;
	}

	// 根据aadl绘图产生的xml文件路径，解析获取所有的thread
	public Set<AADLThread> parseAADLThread(File inputXml) throws Exception {
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(inputXml);
		List<AADLNode> nodeList = parseAADLToNode(document);
		List<AADLLink> linkList = parseAADLToLink(document);
		// id->node
		Map<String, AADLNode> searchMap = new HashMap<String, AADLNode>();
		// id->thread
		Map<String, AADLThread> threads = new HashMap<String, AADLThread>();
		for (int i = 0; i < nodeList.size(); i++) {
			searchMap.put(nodeList.get(i).getId(), nodeList.get(i));
		}

		// 遍历nodelist构建aadlElement
		for (int i = 0; i < nodeList.size(); i++) {
			AADLNode node = nodeList.get(i);
			if (node.getType().equals("thread")) {
				AADLThread thread = new AADLThread();
				// 处理名称
				thread.setName(node.getName());
				// 处理features
				if (node.getFeatures() != null) {
					thread.setPorts(node.getFeatures());
				}

				// 处理parent
				String parentId = node.getParent_id();
				AADLNode parentNode;
				if (parentId != null && !parentId.equals("")
						&& !parentId.equals("null")) {
					parentNode = searchMap.get(parentId);
					thread.setParentNode(parentNode);
				}
				threads.put(node.getId(), thread);
			}
		}
		// 遍历linkList填充threads的connections
		for (int i = 0; i < linkList.size(); i++) {
			AADLLink link = linkList.get(i);
			String sourceid = link.getSourceId();
			String sourcePort = link.getSourcePort();
			String targetid = link.getTargetId();
			String targetPort = link.getTargetPort();
			if (threads.get(sourceid) != null || threads.get(targetid) != null) {
				AADLThread sourceThread = null, targetThread = null;
				if (threads.get(sourceid) != null) {
					sourceThread = threads.get(sourceid);
				}
				if (threads.get(targetid) != null) {
					targetThread = threads.get(targetid);
				}

				PortPair sourcePair = null, targetPair = null;
				AADLFeature sourceFeature = null, targetFeature = null;
				String sourcePortName = "";
				if (sourcePort.contains(":")) {
					sourcePortName = sourcePort.split(":")[1];
					sourceFeature = searchMap.get(sourceid)
							.getAADLFeatureByName(sourcePortName);
				}
				String targetPortName = "";
				if (targetPort.contains(":")) {
					targetPortName = targetPort.split(":")[1];
					targetFeature = searchMap.get(targetid)
							.getAADLFeatureByName(targetPortName);
				}

				targetPair = new PortPair(sourceFeature,
						searchMap.get(sourceid));
				sourcePair = new PortPair(targetFeature,
						searchMap.get(targetid));
				if (targetThread != null && targetFeature != null) {
					if (targetThread.getConnections() != null) {
						targetThread.getConnections().put(targetFeature,
								targetPair);
					} else {
						Map<AADLFeature, PortPair> map = new HashMap<AADLFeature, PortPair>();
						map.put(targetFeature, targetPair);
						targetThread.setConnections(map);
					}
				}

				if (sourceFeature != null && sourceThread != null) {
					if (sourceThread.getConnections() != null) {
						sourceThread.getConnections().put(sourceFeature,
								sourcePair);
					} else {
						Map<AADLFeature, PortPair> map = new HashMap<AADLFeature, PortPair>();
						map.put(sourceFeature, sourcePair);
						sourceThread.setConnections(map);
					}
				}

			}
		}
		Set<AADLThread> result = new HashSet<AADLThread>(threads.values());
		return result;
	}
}
